package xutil

import (
	"log"
	"os"
	"sync"

	"fmt"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type User struct {
	username string
	password string
}

type DBUtil struct {
	session *mgo.Session
	db      *mgo.Database
}

var u *DBUtil
var lock *sync.Mutex = &sync.Mutex{}

func GetInstance() *DBUtil {
	lock.Lock()
	defer lock.Unlock()
	if u == nil {
		u = &DBUtil{}
	}
	return u
}

func (util *DBUtil) Connect() {
	s, err := mgo.Dial("")
	if err != nil {
		println(err.Error())
		os.Exit(1)
	}

	s.SetMode(mgo.Monotonic, true)
	util.session = s
	db := util.session.DB("xnet")
	util.db = db
	log.Println("connect to mongodb")
}

func (util *DBUtil) IsUserExist(username string, c chan bool) {
	var u User
	err := util.db.C("user").Find(bson.M{"username": username}).One(&u)
	if err != nil {
		c <- false
		fmt.Println(err.Error())
	}
	c <- true
}
